﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QuickApp.Core;
using EfSearchModel.Model;
using QuickApp.MVCControl;
using Resto.CostControl.Core;
using QuickApp.MVCControl.Form;
using System.Data.Entity;
using System.Data.SqlClient;

namespace Resto.CostControl.Web.Controllers
{
    public class MaterialPurchaseController : Controller
    {
        private readonly IRepository<MaterialPurchase> _Repo;
        private readonly IRepository<MaterialPurchaseItem> _RepoItem;
        private readonly IUnitOfWork _UnitOfWork;

        public MaterialPurchaseController(IRepository<MaterialPurchase> repo, IRepository<MaterialPurchaseItem> repoDM, UnitOfWork unitOfWork)
        {
            _Repo = repo;
            _RepoItem = repoDM;
            _UnitOfWork = unitOfWork;
        }

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Index(DWZPageInfo pageInfo, DWZQueryModel where)
        {
            //where.AddItem("OrderState", null);
            var list = _Repo.GetPageable(pageInfo.ToPageInfo(), where);
            var fdata = pageInfo.ToFlexiGridData<MaterialPurchase>(list.Page.ToList(), list.Total);
            return Json(fdata);
        }

        public ActionResult Edit(string Id, string supplierId, string date)
        {
            MaterialPurchase data = null;
            if (!string.IsNullOrWhiteSpace(Id))
            {
                data = _Repo.Find(Id);
            }
            else
            {
                data = new MaterialPurchase();
                data.Id = Guid.NewGuid().ToString();
                data.OrderState = "Draft";
                if (!string.IsNullOrEmpty(supplierId))
                {
                    data.SupplierId = ViewBag.SupplierId = supplierId;
                    ViewBag.Date = date;
                    data.OrderDate = DateTime.Parse(date);

                }
                else
                {
                    data.OrderDate = DateTime.Now;
                }
            }
            return View(data);
        }

        [HttpPost]
        public JsonResult Save(MaterialPurchase data, IList<MaterialPurchaseItem> MaterialList)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var ItemDesc = "";
                    decimal TotPrice = 0;
                    if (MaterialList != null)
                    {
                        _RepoItem.DeleteAll(m => m.OrderId == data.Id);

                        foreach (var m in MaterialList)
                        {
                            ItemDesc += m.Name + "，";
                            m.OrderId = data.Id;
                            m.MaterialId = m.Id;
                            m.Id = Guid.NewGuid().ToString();
                            m.State = "Order";
                            TotPrice += m.OrderCount * m.Price;
                            //单位换算（斤=>克）
                            m.OrderCount = m.OrderCount * 500;
                            _RepoItem.Insert(m);
                        }
                    }

                    if (_Repo.Find(data.Id) == null)
                    {
                        data.TotalPrice = TotPrice;
                        data.ItemDesc = ItemDesc.Trim('，');
                        _Repo.Insert(data);
                    }
                    else
                    {
                        var oldData = _Repo.Find(data.Id);
                        TryUpdateModel(oldData);
                        oldData.TotalPrice = TotPrice;
                        oldData.ItemDesc = ItemDesc.Trim('，');
                    }

                    _UnitOfWork.Commit();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            var result = new JsonReturnMessages
            {
                IsSuccess = true,
                Msg = "操作成功",
            };
            return Json(result);
        }

        [HttpPost]
        public JsonResult Delete(string id)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            if (!string.IsNullOrEmpty(id))
            {
                try
                {
                    _Repo.Delete(id);
                    _UnitOfWork.Commit();
                    msg.IsSuccess = true;
                    msg.Msg = "操作成功";
                }
                catch
                {
                    msg.IsSuccess = false;
                    msg.Msg = "操作失败,请稍后重试！";
                }
            }
            else
            {
                msg.IsSuccess = false;
                msg.Msg = "参数错误";
            }
            return Json(msg);
        }
        [HttpPost]
        public JsonResult MaterialList(DWZPageInfo pageInfo, DWZQueryModel where)
        {
            var list = _RepoItem.GetPageable(pageInfo.ToPageInfo(), where);
            var fdata = pageInfo.ToFlexiGridData<MaterialPurchaseItem>(list.Page.ToList(), list.Total);
            return Json(fdata);
        }

        public ActionResult EditList()
        {
            return View();
        }

        [Ninject.Inject]
        public DbContext context { get; set; }

        [HttpPost]
        public JsonResult EditList(string parentId, string supplierId, DateTime? date, DWZPageInfo pageInfo, DWZQueryModel where)
        {
            // 从采购计划中产生明细
            if (!string.IsNullOrEmpty(supplierId))
            {
                string sql = @"select T.MaterialId as Id, '' as OrderId, T.MaterialId, T.Code,T.Name,T.Price,T.Category,SUM(T.PurchaseWeight) as OrderCount 
                                ,0.0 as DeliveryCount, 0.0 as StorageCount, '' as State
                                from 
	                            (
		                            select Id as MaterialId,Code,Name,Price,Category,PurchaseWeight from dbo.V_MaterialPurchasePlan
		                            where Type='RawMaterial' and date = @Date and SupplierId = @SupplierId
		                            union 
		                            select Materials.Id as MaterialId,Materials.Code,Materials.Name,MaterialPrices.Price,Materials.Category,PurchaseWeight*V_MaterialPurchasePlan.ProcessRate as PurchaseWeight
		                            from dbo.V_MaterialPurchasePlan
		                            Inner Join Materials on Materials.Id = V_MaterialPurchasePlan.RawMaterialId
		                            Inner JOin dbo.MaterialPrices ON Materials.Id = dbo.MaterialPrices.MaterialId and dbo.MaterialPrices.IsValid = 1
		                            where V_MaterialPurchasePlan.Type='SemiMaterial' and date = @Date and MaterialPrices.SupplierId = @SupplierId
	                            ) T
	                            Group By T.MaterialId, T.Code,T.Name,T.Price,T.Category";

                List<SqlParameter> plist = new List<SqlParameter>();
                plist.Add(new SqlParameter("@Date", date.Value));
                plist.Add(new SqlParameter("@SupplierId", supplierId));

                var list = context.Database.SqlQuery<MaterialPurchaseItem>(sql, plist.ToArray()).ToList();
                foreach (var item in list)
                {
                    item.OrderCount = item.OrderCount / 500;
                }
                var fdata = pageInfo.ToFlexiGridData<MaterialPurchaseItem>(list, list.Count);
                return Json(fdata);
            }
            else
            {
                where.AddItem("OrderId", parentId == "" ? null : parentId);
                var list = _RepoItem.GetPageable(pageInfo.ToPageInfo(), where);
                var pageList = list.Page.ToList();
                foreach (var item in pageList)
                {
                    item.OrderCount = item.OrderCount / 500;
                }
                var fdata = pageInfo.ToFlexiGridData<MaterialPurchaseItem>(pageList, list.Total);
                return Json(fdata);
            }
        }

        [HttpPost]
        public JsonResult DeleteItem(string Id)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            if (!string.IsNullOrEmpty(Id))
            {
                try
                {
                    _RepoItem.Delete(Id);
                    _UnitOfWork.Commit();

                }
                catch
                {
                    msg.IsSuccess = false;
                    msg.Msg = "操作失败,请稍后重试！";
                }
            }
            else
            {
                msg.IsSuccess = false;
                msg.Msg = "参数错误";
            }
            return Json(msg);
        }


        [HttpPost]
        public JsonResult Delivery(IList<MaterialPurchase> list)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    foreach (var item in list)
                    {
                        var data = _Repo.Find(item.Id);
                        data.OrderState = "fahuo";
                        TryUpdateModel(data);

                        var itemList = _RepoItem.FindAll(m => m.MaterialId == item.Id).ToList();
                        foreach (var childitem in itemList)
                        {
                            var childdata = _RepoItem.Find(childitem.Id);
                            childdata.State = "fahuo";
                            TryUpdateModel(childdata);
                        }
                    }

                    _UnitOfWork.Commit();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            var result = new JsonReturnMessages
            {
                IsSuccess = true,
                Msg = "操作成功",
            };
            return Json(result);
        }

        [HttpPost]
        public JsonResult SingleDelivery(string Id)
        {
            try
            {
                var data = _Repo.Find(Id);
                data.OrderState = "Delivery";

                var itemList = _RepoItem.FindAll(m => m.OrderId == Id).ToList();
                foreach (var childitem in itemList)
                {
                    var childdata = _RepoItem.Find(childitem.Id);
                    childdata.State = "Delivery";
                    childdata.DeliveryCount = childdata.OrderCount;
                }

                _UnitOfWork.Commit();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            var result = new JsonReturnMessages
            {
                IsSuccess = true,
                Msg = "操作成功",
            };
            return Json(result);
        }


    }
}
